<template>
  <div class="mt-1">
    <van-form>
      <van-field
        v-model="value"
        label="工厂代码"
        :label-width="labelWidth"
        clickable
        readonly
        arrow-direction="down"
        is-link
        :value="value"
        placeholder="请选择工厂代码"
        @click="Choose"
      >
      </van-field>
      <van-popup v-model="showPicker" round position="bottom">
        <van-picker
          title="工厂代码"
          show-toolbar
          :columns="plantcode"
          @cancel="showPicker = false"
          @confirm="onAffirm"
        />
      </van-popup>
      <!-- 生产线 -->
      <van-field
        readonly
        clickable
        arrow-direction="down"
        is-link
        label="生产线"
        placeholder="请选择生产线"
        :label-width="labelWidth"
        :value="value_xcx"
        @click="showPicker_xcx = true"
      />
      <van-popup v-model="showPicker_xcx" round position="bottom">
        <van-picker
          title="生产线"
          show-toolbar
          :columns="plantprod"
          @cancel="showPicker_xcx = false"
          @confirm="makeSure"
        />
      </van-popup>

      <!-- 出库人 -->
      <van-field
        v-model="returnPerson"
        label="出库人"
        clearable
        :label-width="labelWidth"
        placeholder="请输入出库人"
      />

      <!-- 拍码 -->
      <van-field
        v-model="code"
        :label-width="labelWidth"
        clearable
        label="拍码"
        ref="code"
        @focus="focus"
        placeholder="请扫描拍码"
      />
      <div class="qrcode" ref="qrCodeUrl"></div>
      <ag-grid-vue
        style="width: 100%; height: 45vh"
        class="ag-theme-alpine mt-1"
        :columnDefs="columnDefs"
        :defaultColDef="defaultColDef"
        :gridOptions="gridOptions"
        rowSelection="single"
        :rowData="rowData"
      >
      </ag-grid-vue>
      <van-row
        gutter="30"
        justify="center"
        type="flex"
        style="margin-top: 1rem"
      >
        <van-col span="7">
          <van-button type="danger" class="mt-1" @click="onRemoveSelected" block
            >删除</van-button
          ></van-col
        >
        <van-col span="7"
          ><van-button type="warning" class="mt-1" @click="updateNum" block
            >修改数量</van-button
          ></van-col
        >
        <van-col span="7"
          ><van-button type="info" class="mt-1" @click="onSubmit" block
            >提交</van-button
          ></van-col
        >
      </van-row>
      <van-popup
        v-model="ShowStatue"
        position="bottom"
        style="height: 100%"
        class="bg-default"
      >
        <show-send-data :ShowDataB="ShowData" @get-val="Sure" />
      </van-popup>
    </van-form>

    <!-- 修改数量的弹窗提示 -->
    <van-dialog
      v-model="ifShowUpdateNum"
      title="拆拍时请确认打印机已连接"
      show-cancel-button
      @confirm="SureUpdate"
    >
      <van-field
        v-model="needUpdateNum"
        type="number"
        placeholder="请输入要修改的数量"
      />
    </van-dialog>
    <!-- 打印信息展示弹框 -->
    <van-popup
      v-model="ifShowPrint"
      position="bottom"
      :style="{ height: '100%' }"
    >
      <div class="contain">
        <div class="message" v-for="item in PrintMsg" :key="item.UniqueId">
          <van-cell title="物料号:" :value="item.ProductId" />
          <van-cell title="拍号:" :value="item.UniqueId" />
          <van-cell title="物料名称:" :value="item.ProductName" />
          <van-cell title="数量:" :value="item.StockQuantity" />
          <van-cell title="单位:" :value="item.Unit" />
          <van-cell title="Mars批次:" :value="item.BatchNO" />
          <van-cell title="供应商批次:" :value="item.SupplyBatchNO" />
          <van-cell title="生产日期:" :value="getZhDate(item.ProductionDate)" />
          <van-cell
            title="生产推荐使用期至:"
            :value="getZhDate(item.ExpDate)"
          />
          <van-cell title="供应商名称:" :value="item.Supplier" />
          <van-cell title="生产商名称:" :value="item.Producer" />

          <!-- <van-cell title="是否冷藏:" value="是 ▢ (<10℃) 否 ▢" />
          <van-cell title="过敏原:" /> -->
          <van-cell title="贴签人:" :value="adminName" />
        </div>
      </div>
      <van-button type="primary" class="mt-1 btn" @click="onPrint" block
        >打印</van-button
      >
    </van-popup>

    <span
      class="tip"
      :style="tip == '未连接' ? 'color : red' : 'color : #0094ff'"
      >打印机:{{ tip }}</span
    >
  </div>
</template>

<script>
import { getpickplant } from "../assets/api/get";
import { InformationSubmit } from "../assets/api/post";
import { parseQRCode, toast, ifOverdure } from "../untils/commion";
import { AgGridVue } from "ag-grid-vue";
import { AgGrid } from "../minx/AgGrid";
import { getDetail } from "../assets/api/post";
import ShowSendData from "../components/ShowSendDate.vue";

export default {
  components: { AgGridVue, ShowSendData },
  mixins: [AgGrid],
  data() {
    return {
      adminName: JSON.parse(localStorage.getItem("username")),
      tip: localStorage.getItem("printMsg"),
      returnPerson: "", //出库人
      needUpdateNum: "", //修改后存放数据
      ifShowUpdateNum: false, //修改数量弹窗
      selectDate: [], //选中的行数据
      labelWidth: "7em",
      titles: new Map().set(6, "生产出库"),
      type: null,
      code: "",
      value: "CN01",
      value_xcx: "",
      plant: "",
      ShowStatue: false,
      showPicker: false,
      showPicker_xcx: false,
      ifShowPrint: false, //是否展示打印弹出层
      columnDefs: [
        { headerName: "物料", field: "productid", flex: 1.5 },
        { headerName: "拍号", field: "uniqueid", flex: 2 },
        { headerName: "数量", field: "stockquantity", flex: 1.5 },
      ],
      copyplantcode: [],
      plantprod: [],
      rowData: [],
      detailData: [],
      plantcode: [],
      ShowData: {}, //展示的数据
      needPrintDate: [], //所有提交时从后台返回的的数据
      PrintMsg: [], //正在需要打印的数据
      ifHeld: [],
      expdate: "",
    };
  },
  watch: {
    code(newValue) {
      if (this.value && this.value_xcx && this.returnPerson) {
        if (newValue.length > 9) {
          let paresqrdata = parseQRCode(newValue);
          if (paresqrdata) {
            if (
              !this.rowData.find((it) => it.uniqueid == paresqrdata.palletNo)
            ) {
              //获取数据
              this.getDetailInfo(paresqrdata.palletNo);
              paresqrdata = "";
              this.code = "";
            } else {
              toast("拍码重复");
              this.code = "";
            }
          } else {
            toast("请检查信息是否完整");
            this.code = "";
          }
        }
      } else {
        toast("请选择工厂和生产线及出库人");
      }
      this.code = "";
    },
  },
  methods: {
    // 获取焦点时触发的方法
    focus() {
      // 获取焦点时阻止键盘弹出
      this.$refs.code.$refs.input.setAttribute("readonly", "readonly");
      setTimeout(() => {
        this.$refs.code.$refs.input.removeAttribute("readonly");
      }, 200);
    },

    setTitle() {
      let res = this.titles.get(this.type);
      this.$store.commit("SET_NAVIGATION", res);
    },
    onRemoveSelected() {
      let selectedData = this.gridApi.getSelectedRows();
      if (this.rowData[0] == null) {
        this.$toast("当前表格为空");
      } else {
        if (selectedData[0] == null) {
          this.$toast("请选择要删除的数据");
        } else {
          let selctIndex = this.gridApi.applyTransaction({
            remove: selectedData,
          });
          // 删除选中的数据
          this.rowData.splice(selctIndex.remove[0].childIndex, 1);
          this.detailData.splice(selctIndex.remove[0].childIndex, 1);
        }
      }
    },
    onAffirm(value) {
      this.value = value;
      this.showPicker = false;
      this.changePlantCode();
    },
    makeSure(value_xcx) {
      this.value_xcx = value_xcx;
      this.showPicker_xcx = false;
    },
    //工厂代码数组
    getPlantCode(PL) {
      for (var i in PL) {
        this.copyplantcode.push(PL[i].plantcode);
      }
      for (var j in this.copyplantcode) {
        if (this.plantcode.indexOf(this.copyplantcode[j]) == -1) {
          this.plantcode.push(this.copyplantcode[j]);
        }
      }
    },
    changePlantCode() {
      let PL = this.plant;
      this.plantprod = [];
      for (var m in PL) {
        if (PL[m].plantcode == this.value) {
          this.plantprod.push(PL[m].plantprod);
        }
      }
    },
    getPlantProd(PL) {
      //生产线数组
      var n = 0;
      for (var m in PL) {
        if (PL[m].plantcode == this.copyplantcode[n])
          this.plantprod.push(PL[m].plantprod);
      }
    },
    Choose() {
      this.showPicker = true;
      this.value_xcx = "";
    },
    //获取后台信息
    async getDetailInfo(val) {
      let res = await getDetail(val);
      if (res.status == 200) {
        this.ShowData = JSON.parse(JSON.stringify(res.data[0]));
        this.expdate = this.ShowData.expdate.substring(0, 10);
        // 判断是否过期
        let now = this.getNowDate();
        let ifguoqi = ifOverdure(now, this.expdate);
        if (ifguoqi) {
          this.$toast("该物料已经过期");
          return;
        }
        if (this.ShowData) {
          this.ShowStatue = true;
          this.rowData.push(res.data[0]);
        }
      } else {
        toast(res.msg);
      }
      this.code = "";
    },
    //传回来把组件关闭
    Sure() {
      setTimeout(() => {
        this.ShowStatue = false;
      }, 100);
      this.getOther();
    },
    //主列表数据
    getOther() {
      this.detailData.push({
        UniqueId: this.ShowData.uniqueid,
        Productid: this.ShowData.productid,
        Num: this.ShowData.stockquantity,
        SortCode: 1,
        kczt: this.ShowData.inventorystatus,
      });
    },
    //获取当前的日期
    getNowDate() {
      let now = new Date();
      let year = now.getFullYear(); //年
      let month = now.getMonth() + 1; //月
      let day = now.getDate(); //日
      return `${year}-${month}-${day}`;
    },
    async onSubmit() {
      if (this.rowData.length == 0) {
        this.$toast("当前表格为空");
      } else {
        let type = "ProductionPicking";
        let submit = {
          BillType: "ProductionPicking",
          BillTypeName: "生产出库",
          OutTime: this.getNowDate(),
          CreatedId: JSON.parse(localStorage.getItem("userid")),
          CreatedName: JSON.parse(localStorage.getItem("username")),
          Plant: this.value,
          WareHouseId_Line: this.value_xcx.substring(0, 4),
          WareHouseName_Line: this.value_xcx,
          Supplier: "",
          txtPassword: "",
          ModifiedOn: "",
          ModifiedName: "",
          CreatedOn: "",
          undefined: "",
          IsLastOut: false,
          Num_Packing: "",
          ProductId_Packing: "",
          Comment: "",
          SupplierId: "",
          LinkNo: "",
          HandUserName: this.returnPerson,
          HandUser: "",
          BillNo: "",
          WareHouseName: "",
          WareHouseId: "",
        };
        this.rowData.forEach((item) => {
          if (item.inventorystatus != "U") {
            this.ifHeld.push(item);
          }
        });
        if (this.ifHeld[0] != null) {
          this.$toast("有冻结物料无法提交");
          this.ifHeld = [];
          return;
        }

        let res = await InformationSubmit(
          type,
          JSON.stringify(submit),
          JSON.stringify(this.detailData)
        );
        if (res.d.state == "success") {
          this.ifSubmit == false;
          this.needPrintDate = [];
          this.PrintMsg = [];
          this.ifHeld = [];
          this.needPrintDate = res.d.data;
          this.needPrintDate.forEach((item) => {
            if (item.UniqueId.substring(0, 4) == "HUAC") {
              this.PrintMsg.push(item);
            }
          });
          // 判断是否有需要打印的数据
          if (this.PrintMsg[0] != null) {
            this.ifShowPrint = true;
          }
          this.$toast({
            type: "success",
            message: "提交成功",
          });
          this.rowData = [];
          this.submitData = [];
          this.detailData = [];
          // if (this.rowData.length == 0) {
          //   toast(res.d.message);
          // }
        } else {
          toast(res.d.message);
        }
      }
    },
    //自动获取工厂信息
    async getBusinessInfo() {
      let res = await getpickplant();
      if (res.status == 200) {
        this.plant = res.data.data;
        this.getPlantCode(this.plant);
        this.getPlantProd(this.plant);
      } else {
        toast("后台发生错误，请与管理员联系");
      }
    },
    //点击弹出修改数量弹窗
    updateNum() {
      this.selectDate = this.gridApi.getSelectedRows();
      if (this.selectDate[0] == null) {
        this.$toast("请选择要修改的数据");
      } else {
        this.ifShowUpdateNum = true;
      }
    },
    // 修改数量确认按钮
    SureUpdate() {
      if (this.needUpdateNum == "") {
        this.$toast("未输入数量无法修改");
      } else {
        this.selectDate[0].stockquantity = this.needUpdateNum;
        this.gridApi.applyTransaction({ update: this.selectDate });
        this.detailData.forEach((item) => {
          if (this.selectDate[0].uniqueid == item.UniqueId) {
            item.Num = Number(this.needUpdateNum);
          }
        });
        this.needUpdateNum = "";
      }
    },
    // 打印按钮
    onPrint() {
      this.ifShowPrint = false;
      setTimeout(() => {
        this.PrintMsg.forEach((item) => {
          this.printQRCode(item);
        });
      }, 500);
    },
    // 获取打印时需要的日期格式
    getZhDate(st) {
      st = st.substring(st.indexOf("(") + 1, st.indexOf(")"));
      let year = new Date(Number(st)).getFullYear();
      let month = new Date(Number(st)).getMonth() + 1;
      let day = new Date(Number(st)).getDate();
      return `${year}-${month}-${day}`;
    },
    // 打印内容
    printSomeTestText(item) {
      window.BTPrinter.setEncoding(
        function () {},
        function () {},
        "GB2312"
      );
      let youxiaoqi = this.getZhDate(item.ExpDate).replace(
        /\d+/g,
        function (a) {
          return a.length == 4 ? a : a.length == 2 ? a : "0" + a;
        }
      );
      let productDate = this.getZhDate(item.ProductionDate).replace(
        /\d+/g,
        function (a) {
          return a.length == 4 ? a : a.length == 2 ? a : "0" + a;
        }
      );
      window.BTPrinter.printTextSizeAlign(
        function () {},
        function () {},
        `      
物料号:${item.ProductId} 拍号:${item.UniqueId}
物料名称:${item.ProductName}
数量:${item.StockQuantity} 单位:${item.Unit}
生产日期:${productDate}
生产推荐使用期至:${youxiaoqi}
Mars批次:${item.BatchNO}
供应商批次:${item.SupplyBatchNO}
供应商名称:
${item.Supplier}
生产商名称:
${item.Producer}
                   
贴签人:${JSON.parse(localStorage.getItem("username"))}                      
  

`,
        "0",
        "1"
      );
    },
    printQRCode(item) {
      let youxiaoqi = this.getZhDate(item.ExpDate).replace(
        /\d+/g,
        function (a) {
          return a.length == 4 ? a : a.length == 2 ? a : "0" + a;
        }
      );
      let productDate = this.getZhDate(item.ProductionDate).replace(
        /\d+/g,
        function (a) {
          return a.length == 4 ? a : a.length == 2 ? a : "0" + a;
        }
      );
      let operDate = productDate.substring(0, 10);
      let NewoperDate = `${operDate.substring(2, 4)}${operDate.substring(
        5,
        7
      )}${operDate.substring(8, 10)}`;
      let expDate = youxiaoqi.substring(0, 10);
      let Newper = `${expDate.substring(2, 4)}${expDate.substring(
        5,
        7
      )}${expDate.substring(8, 10)}`;
      let qrcodenum = `(241)${item.ProductId}(30)${item.StockQuantity}(91)${item.Unit}(10)${item.BatchNO}(11)${NewoperDate}(15)${Newper}(92)${item.SupplierId}(93)${item.ProducerId}(94)${item.UniqueId}(95)(96)(97)${item.SupplyBatchNO}(98)`;
      if (qrcodenum) {
        let _this = this;
        ////////////////////
        var QRCode = require("qrcode");
        QRCode.toDataURL(
          qrcodenum,
          { errorCorrectionLevel: "H", margin: 1, width: 235, height: 235 },
          function (err, url) {
            var image = new Image();
            image.src = url;
            // image.width = 235;
            // image.height = 235;
            image.onload = function () {
              // var canvas = document.createElement("canvas");
              // canvas.height = 260;
              // canvas.width = 260;
              // var context = canvas.getContext("2d");
              // context.drawImage(image, 0, 0);
              // let imageData = canvas
              //   .toDataURL("image/jpeg")
              //   .replace(/^data:image\/(png|jpg|jpeg);base64,/, "");
              window.BTPrinter.printBase64(
                function () {
                  _this.printSomeTestText(item);
                },
                function (err) {
                  if (err) {
                    toast("打印失败请检查打印机是否连接");
                    localStorage.setItem("printMsg", "未连接");
                    _this.tip = localStorage.getItem("printMsg");
                  }
                },
                url,
                "1"
              );
            };
          }
        );
      } else {
        toast("二维码生成失败");
      }
    },
    // 关闭enter键
    closeEnter() {
      document.onkeydown = function (e) {
        //捕捉回车事件
        var ev = typeof event != "undefined" ? window.event : e;
        if (ev.keyCode == 13 || event.which == 13) {
          return false;
        }
      };
    },
  },
  mounted() {
    this.type = parseInt(this.$route.params.type);
    this.setTitle();
    this.getBusinessInfo();
    this.closeEnter();
  },
};
</script>

<style lang="less" scoped>
.ag-theme-alpine .ag-root-wrapper {
  border-left-width: 0;
  border-right-width: 0;
}
.message {
  margin: 1rem auto;
  padding: 0.25rem;
  width: 80%;
  border-radius: 0.5rem;
  border: red 0.05rem solid;
}
.contain {
  height: 35rem;
  overflow: scroll;
}
.btn {
  margin-top: 1rem;
}
.van-loading {
  position: absolute;
  top: 0.7rem;
  right: 0rem;
  z-index: 9999;
}
.tip {
  position: absolute;
  top: 0.7rem;
  right: 1rem;
  z-index: 999;
}
</style>